<template>
  <div class="userinfo">
    <el-tabs v-model="selectTab">
      <el-tab-pane label="个人中心" name="userCenter">
        <div class="user-center">
          <div class="pic" @click="openAvatar">
            <avatar v-if="avatarImg" :size=150 :src="avatarUrl" alt="avatar" key="1"/>
            <avatar v-else :size=150 :word="userInfo.firstName" alt="avatar" key="2"/>
          </div>
          <div class="info">
            <h3>
              {{userInfo.username}}
              <el-tooltip content="修改" placement="bottom" effect="light">
                <i class="iconfont icon-code edit" @click="editUser"></i>
              </el-tooltip>
            </h3>
            <p>性别: {{transformDict('gender', userInfo.gender)}}</p>
            <p>生日: {{userInfo.birthday}}</p>
            <p>邮箱: {{userInfo.email}}</p>
            <p>手机号: {{userInfo.phone}}</p>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="修改密码" name="changePwd">
        <div class="pwd-content">
          <div class="pwd-form">
            <el-form ref="pwdForm" :model="pwdForm" :rules="pwdFormRules" label-position="right" label-width="90px">
              <el-form-item label="原密码:" prop="oldPwd">
                <el-input type="password" v-model="pwdForm.oldPwd" placeholder="请输入原密码" class="pwd-input"></el-input>
              </el-form-item>
              <el-form-item label="新密码:" prop="newPwd">
                <el-input type="password" v-model="pwdForm.newPwd" placeholder="请输入新密码" class="pwd-input"></el-input>
              </el-form-item>
              <el-form-item label="确认密码:" prop="verifyPwd">
                <el-input type="password" v-model="pwdForm.verifyPwd" placeholder="请再次出入密码" class="pwd-input"></el-input>
              </el-form-item>
            </el-form>
            <div class="submit-btn">
              <el-button type="primary" class="pwd-btn" :loading="pwdLoading" @click="changePwd">提 交</el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 修改头像弹框 -->
    <el-dialog :title="avatar.dialogTitle"
      :visible.sync="avatar.dialogVisible"
      width="750px"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false">

      <AvatarCropper ref="avatar" :imgUrl="avatar.imgUrl"></AvatarCropper>

      <span slot="footer" class="dialog-footer">
        <el-button @click="avatar.dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="avatar.loading"  @click="uploadAvatar">提 交</el-button>
      </span>
    </el-dialog>

    <!--dialog弹窗 用户信息-->
    <el-dialog title="修改信息"
      :visible.sync="userDialog.dialogVisible"
      width="30%"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="userForm" :model="userInfo" :rules="userFormRules" label-position="right" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username" placeholder="请输入用户名" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="userInfo.gender" placeholder="请选择性别" class="handle-select">
            <el-option v-for="(g, index) in gender" :key="index" :label="g.name" :value="g.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker align="right" v-model="userInfo.birthday" placeholder="请选择生日" class="handle-date" ></el-date-picker>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email" placeholder="请输入邮箱" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userInfo.phone" placeholder="请输入手机号" class="handle-input"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="userDialog.dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="userDialog.loading"  @click="updateUserinfo">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Avatar from '@/components/Avatar'
import AvatarCropper from '@/components/AvatarCropper'
import {mapGetters} from 'vuex'
import {getLoginUserInfo, logout} from '@/api/login'
import {updateUserinfo as submitUserinfo, updatePassword, uploadAvatar} from '@/api/userinfo'
import {calcMd5} from '@/utils/tool'

export default {
  name: 'userinfo',
  components: {
    Avatar,
    AvatarCropper
  },
  data () {
    var validPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.pwdForm.newPwd) {
        console.log(value)
        console.log(this.pwdForm.newPw)
        callback(new Error('两次密码输入不一致'));
      } else {
        callback();
      }
    }
    return {
      selectTab: 'userCenter',
      userInfo: {},
      avatarUrl: '',
      avatarImg: false,
      userDialog: {
        loading: false,
        dialogVisible: false
      },

      avatar: { // 修改头像弹框
        dialogVisible: false,
        loading: false,
        dialogTitle: '修改头像',
        imgUrl: ''
      },

      pwdLoading: false,
      pwdForm: {
        id: '',
        oldPwd: '',
        newPwd: '',
        verifyPwd: ''
      },

      userFormRules: {
        username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '密码长度为6~20位', trigger: 'blur'}
        ],
        gender: [{required: true, message: '性别不能为空', trigger: 'blur'}],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {type: 'email', message: '邮箱格式错误', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '手机号不能为空', trigger: 'blur'},
          {message: '手机号格式错误', pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, trigger: 'blur'}
        ]
      },

      pwdFormRules: {
        oldPwd: [
          {required: true, message: '原密码不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '密码长度为6~20位', trigger: 'blur'}
        ],
        newPwd: [
          {required: true, message: '新密码不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '密码长度为6~20位', trigger: 'blur'}
        ],
        verifyPwd: [
          {required: true, message: '确认密码不能为空', trigger: 'blur'},
          {validator: validPassword, trigger: 'blur'},
          {min: 6, max: 20, message: '密码长度为6~20位', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    transformDict (key, code) {
      return this.dictinfo(this.GLOBAL.dictKey[key], code);
    },
    updateUserinfo () {
      this.$refs.userForm.validate((valid) => {
        if (!valid) {
          return
        }
        this.userDialog.loading = true;
        submitUserinfo(this.userInfo)
          .then((res) => {
            this.$message.success('修改成功');
            this.userDialog.loading = false;
            this.userDialog.dialogVisible = false;
          })
          .catch(() => {
            this.userDialog.loading = false;
          });
      });
    },
    editUser () {
      // this.userForm = {...this.userInfo};
      this.userDialog.dialogVisible = true;
    },
    openAvatar () {
      if (this.avatarUrl) {
        this.avatar.imgUrl = this.avatarUrl;
      } else {
        this.avatar.imgUrl = require('../../assets/default-avatar.jpg');
      }
      this.avatar.dialogVisible = true;
    },
    uploadAvatar () {
      this.avatar.loading = true;
      let canvas = this.$refs.avatar.getCroppedCanvas();
      if (!canvas) {
        this.$message.error('上传失败');
      }

      canvas.toBlob(blob => {
        let formData = new FormData();
        formData.append('avatar', blob, this.$refs.avatar.getFilename());
        formData.append('userId', this.userInfo.id);
        uploadAvatar(formData).then(res => {
          let url = res.data;
          this.avatarUrl = url;
          // this.avatar.imgUrl = url;
          this.avatarImg = true;
          this.avatar.loading = false;
          this.avatar.dialogVisible = false;
        }).catch(() => {
          this.avatar.loading = false;
        })
      });
    },
    changePwd () {
      this.$refs.pwdForm.validate((valid) => {
        if (!valid) {
          return
        }
        this.pwdLoading = true;
        this.pwdForm.id = this.userInfo.id;

        // 处理密码加密
        var form = {...this.pwdForm}
        form.oldPwd = calcMd5(form.oldPwd);
        form.newPwd = calcMd5(form.newPwd);
        form.verifyPwd = '';
        updatePassword(form)
          .then(res => {
            this.pwdLoading = false;
            this.$message.success('修改成功, 请重新登录');
            logout();
          })
          .catch(() => {
            this.pwdLoading = false;
          })
      });
    }
  },
  computed: {
    ...mapGetters(['dictinfo', 'dictList']),
    gender () {
      return this.dictList(this.GLOBAL.dictKey.gender);
    }
  },
  created () {
    let tab = this.$route.params.tab;
    if (tab) {
      this.selectTab = tab;
    } else {
      this.selectTab = 'userCenter';
    }

    getLoginUserInfo(this.userInfo.id).then((res) => {
      this.userInfo = {...res.data}
      if (this.userInfo.avatar) {
        this.avatarImg = true;
        this.avatarUrl = this.userInfo.avatar;
      }
    });
  }
};
</script>

<style lang="scss" scoped>
.userinfo {

  .pwd-content {
    min-height: 400px;
    display: flex;
    justify-content: center;

    .pwd-form {
      margin-top: 50px;
      width: 50vw;

      .pwd-input {
        width: 300px;
      }

      .submit-btn {
        // text-align: center;
        margin-top: 30px;
        margin-left: 90px;

        .pwd-btn {
          width: 300px;
        }
      }
    }
  }

  .user-center {
    // background-color: aqua;
    display: flex;
    min-height: 400px;
    justify-content: center;

    .pic {
      cursor: pointer;
      margin-top: 50px;
    }

    .info {
      // background-color: bisque;
      width: 50vw;
      margin-top: 50px;
      margin-left: 30px;

      .edit {
        cursor: pointer;
      }
    }
  }
}
</style>
